using NetChinese.Interfaces;
using NetChinese.Models;

namespace NetChinese.Core
{
    /// <summary>
    /// 应用程序类
    /// </summary>
    public class Application
    {
        private readonly IConfigManager _configManager;
        private readonly IToolManager _toolManager;
        private readonly IUIManager _uiManager;
        private readonly ICommandExecutor _commandExecutor;

        public Application(
            IConfigManager configManager,
            IToolManager toolManager,
            IUIManager uiManager,
            ICommandExecutor commandExecutor)
        {
            _configManager = configManager;
            _toolManager = toolManager;
            _uiManager = uiManager;
            _commandExecutor = commandExecutor;
        }

        public async Task RunAsync()
        {
            try
            {
                Console.OutputEncoding = System.Text.Encoding.UTF8;
                Console.WriteLine("=== IntelliSenseLocalizer 中文智能提示安装工具 ===");
                
                await InitializeToolAsync();
                await RunMainLoopAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n发生错误: {ex.Message}");
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }

        private async Task InitializeToolAsync()
        {
            var config = _configManager.LoadConfig();
            
            if (!await _toolManager.CheckToolInstalledAsync())
            {
                Console.WriteLine("未检测到IntelliSenseLocalizer工具，正在安装...");
                await _toolManager.InstallToolAsync();
            }
            else if (config.AutoCheckUpdate)
            {
                await _toolManager.UpdateToolAsync();
            }
        }

        private async Task RunMainLoopAsync()
        {
            var config = _configManager.LoadConfig();
            
            while (true)
            {
                var choice = await _uiManager.ShowMainMenuAsync();
                
                switch (choice)
                {
                    case 0:
                        return;
                    case 1:
                        await InstallIntelliSenseAsync(config);
                        break;
                    case 2:
                        await ManageCacheAsync();
                        break;
                    case 3:
                        await CustomBuildAsync();
                        break;
                    case 4:
                        if (await _uiManager.ShowSettingsAsync(config))
                        {
                            _configManager.SaveConfig(config);
                        }
                        break;
                    default:
                        Console.WriteLine("无效输入，请重新选择！");
                        break;
                }
            }
        }

        private async Task InstallIntelliSenseAsync(Config config)
        {
            var version = await _uiManager.SelectVersionAsync(config.LastVersion);
            var language = await _uiManager.SelectLanguageAsync(config.LastLanguage);
            var compareMode = await _uiManager.SelectCompareModeAsync(config.LastCompareMode);
            
            UpdateConfig(config, version, language, compareMode);
            await _commandExecutor.ExecuteCommandAsync($"islocalizer install auto -m {version} -l {language} -cc {compareMode}");
        }

        private void UpdateConfig(Config config, string version, string language, string compareMode)
        {
            config.LastVersion = version;
            config.LastLanguage = language;
            config.LastCompareMode = compareMode;
            _configManager.SaveConfig(config);
        }

        private async Task ManageCacheAsync()
        {
            if (!await _uiManager.ShowCacheMenuAsync())
            {
                return;
            }

            Console.Write("\n请输入选项(1-3): ");
            if (!int.TryParse(Console.ReadLine(), out int choice))
            {
                Console.WriteLine("无效输入！");
                return;
            }

            switch (choice)
            {
                case 1:
                    Console.WriteLine("正在清理缓存...");
                    await _commandExecutor.ExecuteCommandAsync("islocalizer cache clear");
                    break;
                case 2:
                    Console.WriteLine("正在查看缓存状态...");
                    await _commandExecutor.ExecuteCommandAsync("islocalizer cache -h");
                    break;
                default:
                    Console.WriteLine("无效输入！");
                    break;
            }
        }

        private async Task CustomBuildAsync()
        {
            var (version, language) = await GetBuildParametersAsync();
            if (string.IsNullOrEmpty(version) || string.IsNullOrEmpty(language))
            {
                return;
            }

            await _commandExecutor.ExecuteCommandAsync($"islocalizer build -m {version} -l {language}");
        }

        private async Task<(string version, string language)> GetBuildParametersAsync()
        {
            Console.WriteLine("\n自定义构建：");
            
            Console.WriteLine("请输入要构建的.NET版本（例如：net6.0）：");
            var version = Console.ReadLine()?.Trim();
            
            if (string.IsNullOrEmpty(version))
            {
                Console.WriteLine("版本不能为空！");
                return (null, null);
            }

            Console.WriteLine("请输入要构建的语言（例如：zh-cn）：");
            var language = Console.ReadLine()?.Trim();
            
            if (string.IsNullOrEmpty(language))
            {
                Console.WriteLine("语言不能为空！");
                return (null, null);
            }

            return (version, language);
        }
    }
} 